package com.mzj.saas.jobs.eligible.service;

import com.mzj.saas.jobs.backlog.entity.BacklogItem;
import com.mzj.saas.jobs.backlog.entity.BacklogItemRent;
import com.mzj.saas.jobs.backlog.repository.BacklogItemRentRepository;
import com.mzj.saas.jobs.backlog.repository.BacklogItemRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class EligibleService {
    private static Logger log = LoggerFactory.getLogger(EligibleService.class);

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private BacklogItemRepository backlogItemRepository;
    @Autowired
    private BacklogItemRentRepository backlogItemRentRepository;

    public String work() throws Exception {

        eligibleApplyOverdue();

        return "SUCCESS";
    }

    public void eligibleApplyOverdue() {
        try {
            log.info("eligibleApplyOverdue 资格申请过期 start");

            List<Map<String, Object>> list = jdbcTemplate.queryForList("SELECT id FROM saas_house_eligible_apply WHERE TIMESTAMPDIFF(DAY,apply_time,DATE_FORMAT(NOW(),'%Y-%m-%d %H:%i:%S')) > 180 AND apply_status NOT IN (0,4,6,9) AND match_status != 3");

            int num = jdbcTemplate.update("UPDATE saas_house_eligible_apply SET apply_status = 9 WHERE TIMESTAMPDIFF(DAY,apply_time,DATE_FORMAT(NOW(),'%Y-%m-%d %H:%i:%S')) > 180 AND apply_status NOT IN (0,4,6,9) AND match_status != 3");
            log.info("eligibleApplyOverdue 资格申请过期执行数量 = {}", num);

            //删除配租待办事项
            if (!list.isEmpty()) {
                for (Map map : list) {
                    Long id = (Long) map.get("id");

                    BacklogItemRent backlogItemRent = backlogItemRentRepository.findByApplyId(id);
                    if (backlogItemRent != null){
                        Long backlogItemId = backlogItemRent.getBacklogItemId();
                        Optional<BacklogItem> itemOpt = backlogItemRepository.findById(backlogItemId);
                        if (itemOpt.isPresent()) {
                            BacklogItem backlogItem = itemOpt.get();
                            backlogItemRepository.delete(backlogItem);
                        }

                        backlogItemRentRepository.delete(backlogItemRent);
                    }
                }
            }

            log.info("eligibleApplyOverdue 资格申请过期  end");
        } catch (Exception e) {
            log.error("资格申请过期" + e.getMessage(), e);
        }
    }


}
